package com.huonan.jb.tools.monitor;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.mininglamp.bia.msg.utils.WXMessageUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 日志监控
 * @Author lxp
 * @Date 2022/9/29 下午3:46
 * @Version V1.0
 **/
@Slf4j
public class HiveTaskMonitor {

    //报警阈值 分钟
    private static final int TIME_THRESHOLD = 180;
    private static final String LOGS_BASE_PATH = "/home/quantum_social/mysql_to_hdfs/scrips/bayou/%s/logs/";
    private static final String ec_log_path = "/home/quantum_social/mysql_to_hdfs/scrips/bayou/ec/logs/%s/%s";
    private static final String wenda_log_path = "/home/quantum_social/mysql_to_hdfs/scrips/bayou/wenda/logs/%s/%s";
    private static final List<String> ecFilterFile = Arrays.asList("ec_comment_dws_cron.log");
    private static final List<String> wendaFilterFile = Arrays.asList(
            "wenda_answer_dws_cron.log", "wenda_comment_dws_cron.log", "wenda_user_dws_cron.log");


    public static void main(String[] args) {
        doRun();
    }

    private static void doRun() {
        List<String> platform = ListUtil.of("ec", "wenda");

//            extractHandle(plat, yesterday);
        for (String f : ecFilterFile) {
            String tPath = String.format(ec_log_path, DateUtil.today(), f);
            scanLog(tPath);
        }

        for (String f : wendaFilterFile) {
            String tPath = String.format(wenda_log_path, DateUtil.today(), f);
            scanLog(tPath);
        }
    }

    private static void handle(String plat, String day) {
        String tPath = String.format(LOGS_BASE_PATH + "%s", plat, day);
        scanLog(tPath);
    }

    private static void scanLog(String filePath) {
        if (!FileUtil.isFile(filePath)) {
            log.error("filePath:{}", "no have this file");
            alarm(filePath, 0);
            return;
        }
        log.info("path:{}", filePath);
        log.info("start");
        Path path = FileSystems.getDefault().getPath(filePath);
        BasicFileAttributes attributes = FileUtil.getAttributes(path, false);
        long taskMills = attributes.lastModifiedTime().toMillis();
        long now = System.currentTimeMillis();
        long diff = (now - taskMills) / 1000 / 60;
        if (diff > TIME_THRESHOLD) {
            Date date = new Date(taskMills);
            String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
            log.error("file:{},date:{},diff:{}", filePath, format, diff);
            alarm(filePath, 0);
        }
        //extracted(files);
        log.info("end");
    }

    //获取文件内容
    private static void extracted(List<File> files) {
        System.out.println(files);
        files.stream()
                .filter(f -> f.getName().contains("dws"))
                .forEach(f -> {
                    List<String> list = FileUtil.readUtf8Lines(f);
                    long minute = obtainCost(list);
                    if (minute >= TIME_THRESHOLD) {
                        //alarm(f.getName(), minute);
                    }
                });
        log.info("end");
    }

    private static Long obtainCost(List<String> list) {
        if (list.size()==0) {
            return 0L;
        }
        String lastLine = list.get(list.size() - 1);
        String startDate = obtainDate(lastLine);
        long startTimeStamp = formatToTimeStamp(startDate);
        if (startTimeStamp == 0) {
            log.info("任务执行完成");
            return 0L;
        }
        long duration = DateUtil.spendMs(startTimeStamp);
        return TimeUnit.MILLISECONDS.toMinutes(duration);
    }

    private static String obtainDate(String text) {
        String result = "";
        if (!text.contains("Join  completed")) {
            String pattern = "\\[(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})\\]";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(text);
            if (m.find()) {
                result = m.group(1);
            }
        }
        return result;
    }

    private static Long formatToTimeStamp(String input) {
        Long result = 0L;
        if (StrUtil.isNotEmpty(input)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
            Date date;
            try {
                date = format.parse(input);
            } catch (Exception e) {
                log.error("解析日期错误：{}", input);
                return result;
            }
            return date.getTime();
        }
        return result;
    }

    private static void alarm(String name, long minute) {
        String content = String.format("任务: %s", name);
        //发微信群
        List<String> mobileNums = new ArrayList<>();
        mobileNums.add("18582463486");
        WXMessageUtil.sendMessage(content, mobileNums);
    }
}



